<!DOCTYPE html>
<html>
<head>
<!-- 页面改动总结   3个同步请求改为异步请求 
		block mlist review
	1. 删除review.jsp 改为用模态框modal 
	2. select 改为监听onchange事件 直接提交请求
	3. !!!Attention!!!
		用了全局变量 : 在m处于待审核状态时，点击edit会设置globalMId
	4. 任何修改提交后都可以直接用 selectType(reviewType);		// 异步刷新列表显示
	5. 全局变量，当前setInterval 函数的返回值，用于停止setTimeout
-->
<meta charset="UTF-8">
<title>review merchants' application</title>
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap.js"></script>
<link href="bootstrap.css" rel="stylesheet"  type="text/css">  
<script>
	// interval 轮询
	// setInterval clearInterval
	var interval;

	// 页面初始化
	// 第一次加载页面的时候 发送 审核状态为all的请求	
	$(function () {
		$('#selectType').val('ALL');
		selectType();
		poll();
	});
	
	// 轮询服务器 获取最新的MList
	function poll() {
		console.log('polling');		
		interval = setInterval("pollMList()", 500);  
	}
	
	function pollMList() {
		var url = 'PollServlet';
		$.getJSON(url, function(isNewest) {
// 			console.log('pollMList : is Newest : ' + isNewest)
			if (isNewest == 'newest') {
				// 最新的
			} else if (isNewest == 'notNewest') {
// 				alert('new Merchant registrations');
				selectType();
			}
		});
	}
		
	// 包装 table的一行
	function decorate(m) {
 		var w = (x) => '<td>' + (x === undefined ? ' ' : x) + '</td>';	// 括号 优先级
		var idcard = '<img src="ImageServlet?mId=' + m.mId +'&pictureType=image" alt="broken image"  height="100px"  width="100px"/>'
		var image = '<img src="ImageServlet?mId=' + m.mId +'&pictureType=idCard" alt="broken image"  height="100px"  width="100px"/>'
		// 可选操作 operation  判断type(审核状态：审核中，审核不通过，驳回）显示对应的操作
		var operation = '';
		if (m.type == 'ASSESSING') {	 
			operation ='<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#reviewModal" onclick="globalMId=\'' + m.mId + '\';">edit</button>';
		} else if (m.type == 'REJECT') {
			operation = '';
		} else if (m.type == 'ASSESSED') {
			if (m.status == 'BLACK') {
				operation = '<button type="button" onclick=\"switchBlock(\'' + m.mId + '\', this);">undo block</button>';	 					
			} else if (m.status == 'WHITE') {
				operation = '<button type="button" onclick="switchBlock(\'' + m.mId + '\', this);">block</button>';
			}
		}
		var ret = '<tr>' + w(m.mName) + w(idcard) + w(image) + w(m.address) + w(m.type) + w(m.reason) + w(m.status) + w(operation) +'</tr>';
		return ret;
	}
	
	// block ajax	拉黑拉白 同步改为异步		服务器返回true字符串，则认为拉黑成功
	function switchBlock(mId, btn) {
		console.log('switch block' + mId);
		url = 'BlockServlet?mId=' +mId;
		var btn = $(btn);
		var status = $(btn.parent().prev());		// 用parent() prev()拿status
		
		$.getJSON(url, function(isChange){
			if (isChange == 'success') {		// !成功后也可以直接selectType 直接更新整个列表。。。。。。
				btn.text() == 'block' ? btn.text('undo block') : btn.text('block');
				status.text() == 'WHITE' ? status.text('BLACK') : status.text('WHITE'); 
				console.log('switchBlock : success! new block and status are : ' , btn.text(), status.text());
			} else {
				alert('switch block failed!');
			}
		});
	}
	
	// review ajax 审核后提交 同步改异步
	function review() {		
		var reviewType = $("#review_selectType").val();
		var reviewReason = $("#review_reason").val();
		console.log('review: type : ' + reviewType + " reason : " + reviewReason);
		var url = 'ReviewServlet?mId=' + globalMId + '&type=' + reviewType + '&reason=' + reviewReason;
		$.getJSON(url, function(data) {
			if (data == 'success') {
				selectType(reviewType);		// 异步刷新列表显示	
			} else {
				alert('edit review failed!');
			}			
		});
	}
	 
	// 选择审核状态，处理返回的（指定审核状态的）商家列表
	function selectType() {		// 选择审核状态type，ajax异步提交表单		
		var selectedOption = $('#selectType').val();
		console.log('选择审核状态： ' + selectedOption);
		var url = 'MListServlet?type=' + selectedOption;
		console.log('url is : ' + url);
		$.getJSON(url, function(data) {
			$('#listTBody').html('');		// 清空一下先
// 		$.getJSON('allMerchants.json', function(data) {	// 测试用
			console.log('Server return : ' + data);
			// 返回M列表，处理成table的每一行
			data.forEach(function(item, index, array){
// 				console.log(item);
				$('#listTBody').append(decorate(item));
			});
		});
			
			
		// 显示模态框时 保持轮询
		$('#reviewModal').on('show.bs.modal', function() {
			console.log('hide modal : stop polling');
			clearInterval(interval);
		});		
		// 隐藏模态框时 停止轮询 用show.bs.modal
		$('#reviewModal').on('hide.bs.modal', function(){
			console.log('hide modal : restore polling');
			clearInterval(interval);
			poll();				
		});
		
		
	}
</script>
</head>
<body>
	<a align="left" href="LogoutServlet">logout</a>
	<!-- mlist页面  -->
	<!-- 	 选择 type的下拉框
		1. type 为审核状态 assessing assessed reject All
		2. ajax 
				send : 监听select onchange事件
				recv : 不需要！！因为不会改变 
	-->
	<h1>select type</h1>
	<select id="selectType" onchange='selectType();'>
		<option value="ALL">ALL</option>
		<option value="ASSESSING">ASSESSING</option>
		<option value="ASSESSED">ASSESSED</option>
		<option value="REJECT">REJECT</option>
	</select>
	<hr>
	<h1>AMerchant List</h1>
	<table id='listTable'  class="table table-bordered table-hover table-condensed" width="50%">
		<tr>
			<td>name</td>
			<td>image</td>
			<td>IDCard</td>
			<td>address</td>
			<td>type</td>
			<td>reason</td>
			<td>status</td>
			<td>operation</td>
		</tr>
		  <tbody id='listTBody'  >
		  </tbody>
	</table>

	<!-- Modal -->
	<div class="modal fade" id="reviewModal" tabindex="-1" role="dialog"
		aria-labelledby="exampleModalLabel" aria-hidden="true">
		<div class="modal-dialog" role="document">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="exampleModalLabel">Update
							Merchant Status</h5>
						<button type="button" class="close" data-dismiss="modal"
							aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="modal-body">
						<div>
							<select id="review_selectType" name="type">
								<option value="ASSESSING">ASSESSING</option>
								<option value="ASSESSED">ASSESSED</option>
								<option value="REJECT">REJECT</option>
							</select>
						</div>
						<textarea id="review_reason" name="reason" cols="100" rows="5"></textarea>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary"
							data-dismiss="modal">Close</button>
						<button type="button" class="btn btn-primary" onclick="review();" data-dismiss="modal">Save
							changes</button>
					</div>
				</div>
			</div>
		</div>
	</div>

</body>
</html>